<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: {2021/1/11}
 * Time: {16:27}
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\api\business;

use app\common\lib\ClassArr;
use app\common\lib\Num;
use app\common\validate\User;
use think\Exception;
use think\facade\Cache;

class Sms
{
    /**
     * @param array $data
     * @param int $len
     * @param string $type
     * @return bool
     * @throws Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \ReflectionException
     */
    public function sendCode(array $data, int $len = 4, string $type = 'ali'): bool
    {
        $validate = new User();
        if (!$validate->scene('sms')->check($data)) {
            throw new Exception($validate->getError());
        }
        //调用
        $code = Num::randNum($len);
        try {
            $classArray = ClassArr::SmsClassStat();
            $classObj = ClassArr::initClass($type, $classArray);
            $result = $classObj::sendSms($data['phone_number'], $code);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
        if ($result) {
            //记录到redis
            Cache::store('redis')->set("send_sms_code" . $data['phone_number'], $code, config('status.redis.session_ssl'));
            return true;
        } else {
            return false;
        }
    }
}